<template>
   
  <div class="pagination">
    <!-- 当当前页为第一页的时候，这个按钮应该禁用 -->
    <button :disabled="pageNo === 1" @click="$emit('changePageNo',pageNo-1)">上一页</button>
    <!-- 当连续页码的起始页码大于1的时候，这个1才会显示 -->
    <button v-if="startAndEnd.start > 1" @click="$emit('changePageNo',1)">1</button>
    <!-- 当连续页码的起始页码大于2的时候，才需要展示... -->
    <button v-if="startAndEnd.start > 2">···</button>

    <button
      :class="{active:pageNo===item + startAndEnd.start -1}"
      v-for="(item,index) in startAndEnd.end - startAndEnd.start +1"
      :key="index"
      @click="$emit('changePageNo',item + startAndEnd.start -1)"
    >
      {{ item + startAndEnd.start -1 }}
    </button>

    <!-- 当连续页码的结束页码小于  总页码-1 才需要展示... -->
    <button v-if="startAndEnd.end < totalPage - 1">···</button>
    <!-- 当连续页码的结束码小于总页码才会展示这个总页码 -->
    <button v-if="startAndEnd.end < totalPage" @click="$emit('changePageNo',totalPage)">{{ totalPage }}</button>
    <!-- 当前页是最后一页 禁用下一页按钮 -->
    <button :disabled="pageNo === totalPage" @click="$emit('changePageNo',totalPage+1)">下一页</button>
    <button style="margin-left: 30px">共{{ total }}条</button>
  </div>
</template>



<script>
export default {
  name: "PageNation",
  props: {
    total: {
      //总条数
      required: true,
    },
    pageSize: {
      //每一页多少条
      type: Number,
      default: 5,
    },
    continues: {
      //页面连续几条
      type: Number,
      default: 5,
    },
    pageNo: {
      //当前是多少页
      type: Number,
      default: 1,
    },
  },
  computed: {
    // 计算总页数
    totalPage() {
      return Math.ceil(this.total / this.pageSize);
    },
    // 计算中间连着的页码的起始页和结束页
    startAndEnd() {
      let { totalPage, pageNo, continues } = this;
      let start;
      let end;
      if (totalPage < continues) {
        //1.当总页数小于连续页码数，那么应该1~总页码数
        start = 1;
        end = totalPage;
      } else {
        //当总页数大于等于连续页码数
        start = pageNo - (continues - 1) / 2;
        end = pageNo + (continues - 1) / 2;
        if (start < 1) {
          //2.假设当前页码为1，按上面计算就是 -1 0 1 2 3 ，超出了，需要校正一下==》1 2 3 4 5
          start = 1;
          end = continues;
        }
        if (end > totalPage) {
          //3.假设当前页码为9 总页码为10，按照上面计算就是 7 8 9 10 11，超出了，需要校正==》6 7 8 9 10
          start = totalPage - continues + 1;
          end = totalPage;
        }
      }
      return { start, end };
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;
    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }
    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
